package com.fdm.model.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fdm.model.Book;
import com.fdm.util.exceptions.UniqueConstraintException;
@Repository
public class HibernateBookDAOImpl implements BookDAO {
	@Autowired
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void newBook(Book book) throws UniqueConstraintException{
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try{
			session.save(book);
			session.getTransaction().commit();
		}
		catch (ConstraintViolationException cve){
			session.getTransaction().rollback();
			throw new UniqueConstraintException("A book with the ISBN number "+book.getIsbn()+" has already been created");
		}
		finally{
			session.close();
		}
	}

	public Book getBook(long id) {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		Book book=(Book)session.get(Book.class, id);
		session.close();
		return book;
	}

	public List<Book> searchBooks(String seachString) {
		// TODO Auto-generated method stub
		return null;
	}

	public void removeBookFromInventory(long id) {
		// TODO Auto-generated method stub

	}

}
